import {
  Button,
  ButtonGroup,
  Center,
  HStack,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Popover,
  PopoverContent,
  PopoverTrigger,
  SimpleGrid,
  Stack,
  useDisclosure,
  useToast,
  VStack,
} from "@chakra-ui/react";
import React from "react";
import { useState } from "react";
import { MdAdd, MdClose } from "react-icons/md";
import ReactFocusLock from "react-focus-lock";
import { useQuery } from "react-query";
import { UserType } from "../../pages/Mission";

const AddPopover: React.FC<{
  tags: string[];
  onTagsChange: (tag: string) => void;
}> = ({ tags, onTagsChange }) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  return (
    <>
      <Popover isOpen={isOpen} onClose={onClose}>
        <PopoverTrigger>
          <Button
            size={"lg"}
            borderRadius={"full"}
            variant={"outline"}
            colorScheme={"blue"}
            leftIcon={<MdAdd />}
            onClick={onOpen}
          >
            添&nbsp;&nbsp;加
          </Button>
        </PopoverTrigger>
        <PopoverContent>
          <ReactFocusLock returnFocus persistentFocus={false}>
            <Form tags={tags} onTagsChange={onTagsChange} onClose={onClose} />
          </ReactFocusLock>
        </PopoverContent>
      </Popover>
    </>
  );
};

const Form: React.FC<{
  tags: string[];
  onTagsChange: (tag: string) => void;
  onClose: () => void;
}> = ({ tags, onTagsChange, onClose }) => {
  const [value, setValue] = React.useState("");
  const handleChange = (event: {
    target: { value: React.SetStateAction<string> };
  }) => setValue(event.target.value);

  const toast = useToast();
  const onClick = () => {
    if (value === "") {
      toast({ title: "标签不能为空" });
    } else if (tags.includes(value)) {
      toast({ title: "请勿重复添加" });
    } else {
      onClose();
      setValue("");
      onTagsChange(value);
    }
  };

  return (
    <>
      <Stack spacing={4}>
        <Input
          value={value}
          onChange={handleChange}
          placeholder="请输入标签"
          size="lg"
        />
        <ButtonGroup d="flex" justifyContent="flex-end">
          <Button colorScheme="primary" mr={3} onClick={onClick}>
            确认
          </Button>
          <Button variant="ghost" onClick={onClose}>
            取消
          </Button>
        </ButtonGroup>
      </Stack>
    </>
  );
};

export const TagSelectModal: React.FC<{
  isOpen: boolean;
  onClose: () => void;
}> = ({ isOpen, onClose }) => {
  useQuery<UserType, any>("profile", () =>
    fetch("/api/profile", {
      headers: {
        Authorization: "Bearer " + String(localStorage.getItem("accessToken")),
      },
    })
      .then((res) => res.json())
      .then((res) => {
        setMyTags((prv) => {
          return res.tags.concat(prv.filter((v) => !res.tags.includes(v)));
        });
        setAllTags((prv) => {
          return res.tags.concat(prv.filter((v) => !res.tags.includes(v)));
        });
        return res;
      })
  );
  const { data: defaultTags } = useQuery<string[], any>("tags", () =>
    fetch("/api/tags")
      .then((res) => res.json())
      .then((res) => {
        setAllTags((prv) => {
          return res.tags.concat(prv.filter((v) => !res.tags.includes(v)));
        });
        return res.tags;
      })
  );

  const my: string[] = [];
  const [myTags, setMyTags] = useState(my);
  const [allTags, setAllTags] = useState(my);

  const onTagClick = (tag: string) => {
    myTags.includes(tag)
      ? setMyTags((prv) => prv.filter((x) => x !== tag))
      : setMyTags((prv) => [...prv, tag]);
  };

  const onAddTagClick = (tag: string) => {
    onTagClick(tag);
    if (!allTags.includes(tag)) {
      setAllTags((prv) => [...prv, tag]);
    }
  };

  const onConfirmClick = () => {
    fetch("/api/profile", {
      method: "PUT",
      body: JSON.stringify({
        tags: myTags,
      }),
      headers: {
        "content-type": "application/json",
        Authorization: "Bearer " + String(localStorage.getItem("accessToken")),
      },
    })
      .then((res) => {
        if (res.ok) {
          toast({ title: "修改成功" });
          return res.json();
        } else {
          toast({ title: "修改失败" });
        }
      })
      .catch((err) => {
        toast({ title: "修改失败" });
      });
    onClose();
    setAllTags((prv) => {
      return prv.filter((v) => defaultTags?.includes(v) || myTags.includes(v));
    });
  };

  const toast = useToast();

  return (
    <Modal isOpen={isOpen} onClose={onClose} size={"xs"} isCentered={true}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>选择您感兴趣或擅长的领域</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <Center>
            <HStack spacing={6} align={"flex-start"}>
              <VStack>
                <AddPopover tags={allTags} onTagsChange={onAddTagClick} />
                {allTags?.slice(0, allTags.length / 2).map((tag) => (
                  <Button
                    size={"lg"}
                    key={tag}
                    borderRadius="full"
                    variant={myTags.includes(tag) ? "solid" : "outline"}
                    colorScheme="blue"
                    onClick={() => onTagClick(tag)}
                  >
                    {tag}
                  </Button>
                ))}
              </VStack>
              <VStack>
                {allTags
                  ?.slice(allTags.length / 2, allTags.length)
                  .map((tag) => (
                    <Button
                      size={"lg"}
                      key={tag}
                      borderRadius="full"
                      variant={myTags.includes(tag) ? "solid" : "outline"}
                      colorScheme="blue"
                      onClick={() => onTagClick(tag)}
                    >
                      {tag}
                    </Button>
                  ))}
              </VStack>
            </HStack>
          </Center>
        </ModalBody>
        <ModalFooter>
          <Button colorScheme="primary" mr={3} onClick={onConfirmClick}>
            确认
          </Button>
          <Button variant="ghost" onClick={onClose}>
            取消
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export const TagInit: React.FC<{
  myTags: string[];
  setMyTags: React.Dispatch<React.SetStateAction<string[]>>;
}> = ({ myTags, setMyTags }) => {
  const { data: defaultTags } = useQuery<string[], any>("tags", () =>
    fetch("/api/tags")
      .then((res) => res.json())
      .then((res) => {
        setAllTags((prv) => {
          return res.tags.concat(prv.filter((v) => !res.tags.includes(v)));
        });
        return res.tags;
      })
  );

  const my: string[] = [];
  const [allTags, setAllTags] = useState(my);

  const onTagClick = (tag: string) => {
    myTags.includes(tag)
      ? setMyTags((prv) => prv.filter((x) => x !== tag))
      : setMyTags((prv) => [...prv, tag]);

    if (allTags.includes(tag) && !defaultTags?.includes(tag)) {
      setAllTags((prv) => prv.filter((x) => x !== tag));
    } else if (!allTags.includes(tag)) {
      setAllTags((prv) => [...prv, tag]);
    }
  };

  return (
    <Center>
      <SimpleGrid columns={3} spacing={4}>
        <AddPopover tags={allTags} onTagsChange={onTagClick} />
        {allTags?.map((tag) => (
          <Button
            size={"lg"}
            key={tag}
            borderRadius="full"
            variant={myTags.includes(tag) ? "solid" : "outline"}
            colorScheme="blue"
            onClick={() => onTagClick(tag)}
            rightIcon={defaultTags?.includes(tag) ? undefined : <MdClose />}
          >
            <Center>{tag}</Center>
          </Button>
        ))}
      </SimpleGrid>
    </Center>
  );
};
